package com.presto.directo.mvvm.view

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.*
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.presto.directo.R
import com.presto.directo.base.BaseFragment
import com.presto.directo.databinding.FragmentFailBinding
import com.presto.directo.entity.AppEntity
import com.presto.directo.net.*
import com.presto.directo.utils.*
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.internal.functions.Functions
import java.net.*

class FailFragment : BaseFragment() {

    private val binding by lazy { FragmentFailBinding.inflate(layoutInflater) }

    private val baseQuickAdapter by lazy {
        object : BaseQuickAdapter<AppEntity, BaseViewHolder>(R.layout.item_other_app) {
            override fun convert(holder: BaseViewHolder, item: AppEntity) {
                holder.setText(R.id.tv_name, item.name)
                val iv = holder.getView<ImageView>(R.id.iv_icon)
                if (item.imgUrl.isNotBlank()) {
                    Glide.with(this@FailFragment).load(item.imgUrl).dontAnimate().into(iv)
                } else {
                    iv.setImageDrawable(null)
                }
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    override fun initEvent() {
        super.initEvent()
        binding.rvApp.layoutManager = LinearLayoutManager(context).apply { orientation = RecyclerView.VERTICAL }
        binding.rvApp.adapter = baseQuickAdapter
        baseQuickAdapter.setOnItemClickListener { adapter, view, position ->
            val appInfo = baseQuickAdapter.getItem(position)
            if (appInfo.url.isNullOrBlank()) {
                return@setOnItemClickListener
            }
            Observable.just(baseQuickAdapter.getItem(position).url)
                .map {
                    val httpURLConnection = URL(it).openConnection() as HttpURLConnection
                    httpURLConnection.instanceFollowRedirects = false
                    if (httpURLConnection.responseCode == 302) {
                        httpURLConnection.getHeaderField("Location")
                    } else {
                        it
                    }
                }
                .applySchedulers()
                .doOnSubscribe { showProgress() }
                .doFinally { dismissProgress() }
                .bindLifeCycle(this)
                .subscribe({
                    val uri = Uri.parse(it)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }, Functions.emptyConsumer())
        }
        start(onNext = {
            val apps = getApiService().getOtherAppList(getHttpMap().sign(47)).getResult().advertising
            if (!apps.isNullOrEmpty()) {
                baseQuickAdapter.addData(apps)
            }
        }, toast = false)
    }

    companion object {
        fun createFragment(): Fragment {
            return FailFragment()
        }
    }
}